package com.xxx.car.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.xxx.car.cache.CarRedisTemplate;
import com.xxx.car.constants.MsgStatus;
import com.xxx.car.constants.RedisConstants;
import com.xxx.car.entity.TbUserMsg;
import com.xxx.car.entity.vo.request.ReqUserMsg;
import com.xxx.car.entity.vo.request.ReqUserMsgQuery;
import com.xxx.car.entity.vo.response.RespUserMsg;
import com.xxx.car.service.UserMsgService;
import com.xxx.car.mapper.TbUserMsgMapper;
import com.xxx.common.push.exception.PushException;
import com.xxx.common.push.msg.MsgPayload;
import com.xxx.common.push.umeng.UmengPush;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by xuwenjie on 2017/6/14.
 */
@Service
public class UserMsgServiceImpl implements UserMsgService {

    private static final Logger LOG = LoggerFactory.getLogger(UserMsgServiceImpl.class);

    @Autowired
    private TbUserMsgMapper tbUserMsgMapper;

    @Autowired
    private CarRedisTemplate carRedisTemplate;

    @Autowired
    private UmengPush umengPush;


    @Override
    public List<RespUserMsg> findByPage(ReqUserMsgQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<TbUserMsg> res = tbUserMsgMapper.query(query);
        return res.stream().map(e -> {
            RespUserMsg respUserMsg = new RespUserMsg();
            BeanUtils.copyProperties(e, respUserMsg);
            return respUserMsg;
        }).collect(Collectors.toList());
    }

    @Override
    public RespUserMsg getByIdAndUser(Integer userId, Integer msgId) {
        TbUserMsg msg = tbUserMsgMapper.getByIdAndUserId(msgId, userId);
        if (msg != null) {
            RespUserMsg res = new RespUserMsg();
            BeanUtils.copyProperties(msg, res);
            return res;
        }
        return null;
    }

    @Override
    public void modifyStatus(Integer msgId, int status) {
        tbUserMsgMapper.modifyStatus(msgId, status);
    }

    @Override
    public void delteByIdAndUser(Integer userId, List<Integer> msgIds) {
        tbUserMsgMapper.deleteByIdAndUserId(msgIds, userId);
    }

    @Override
    public void addMsg(ReqUserMsg reqUserMsg) {
        Date now = new Date();
        TbUserMsg tbUserMsg = new TbUserMsg();
        tbUserMsg.setUserId(reqUserMsg.getUserId());
        tbUserMsg.setMsgTitle(reqUserMsg.getMsgTitle());
        tbUserMsg.setMsgContent(reqUserMsg.getMsgContent());
        tbUserMsg.setMsgType(reqUserMsg.getMsgType());

        tbUserMsg.setMsgStatus(MsgStatus.NO_READ);
        tbUserMsg.setCreateTime(now);
        tbUserMsg.setUpdateTime(now);

        tbUserMsgMapper.insertSelective(tbUserMsg);

        String deviceToken = (String) carRedisTemplate.get(RedisConstants.USER_DEVICE_TOKEN + reqUserMsg.getUserId());
        if (StringUtils.isNotBlank(deviceToken)) {
            MsgPayload payload = new MsgPayload();
            payload.setTitle(reqUserMsg.getMsgTitle());
            payload.setText(reqUserMsg.getMsgContent());
            payload.setTicker(reqUserMsg.getMsgContent());
            try {
                umengPush.push(payload, Arrays.asList(deviceToken));
            } catch (PushException e) {
                LOG.error("消息->{},推送失败->{}", JSON.toJSONString(payload), e.getMessage());
            } catch (IOException e) {
                LOG.error(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}
